package JUC.轮流打印1_100;

public class AlternatePriting2 {
    private int currentNum = 1;
    private static final Object lock = new Object();

    public static void main(String[] args) {
        AlternatePriting2 al = new AlternatePriting2();
        new Thread(() -> al.printNum(true)).start();
        new Thread(() -> al.printNum(false)).start();
    }

    private void printNum(boolean isOdd) {
        while (currentNum < 100) {
            synchronized (lock) {
                while ((isOdd && currentNum % 2 == 0) || (!isOdd && currentNum % 2 == 1)) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                if (currentNum <=100) {//不加这个，有个被阻塞的会打印101，是偶数线程
                    System.out.println(Thread.currentThread().getName() + ":" + currentNum);
                    currentNum++;
                    lock.notifyAll();
                }
            }
        }

    }

}
